package com.hjm.project.formalPos.formalPos.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hjm.common.utils.StringUtils;
import com.hjm.common.utils.Utils;
import com.hjm.common.utils.security.ShiroUtils;
import com.hjm.common.utils.yh.PoiUtil;
import com.hjm.project.ActActive.ActActive.domain.ActActive;
import com.hjm.project.ActActive.ActActive.service.IActActiveService;
import com.hjm.project.agentInfo.agentInfo.domain.AgentInfo;
import com.hjm.project.agentInfo.agentInfo.service.IAgentInfoService;
import com.hjm.project.formalPos.branchPos.domain.BranchPos;
import com.hjm.project.formalPos.branchPos.service.IBranchPosService;
import com.hjm.project.record.activityRecord.domain.ActivityUpdateRecord;
import com.hjm.project.record.activityRecord.service.IActivityUpdateRecordService;
import com.hjm.project.record.purchaserRecord.domain.PurchaserUpdateRecord;
import com.hjm.project.record.purchaserRecord.service.IPurchaserUpdateRecordService;
import com.hjm.project.terminal.library.domain.TerminalLibrary;
import com.hjm.project.terminal.library.service.ITerminalLibraryService;
import com.hjm.project.terminal.manufacturer.service.IManufacturerService;
import com.hjm.project.terminal.record.domain.PosOperateModel;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.hjm.framework.aspectj.lang.annotation.Log;
import com.hjm.framework.aspectj.lang.enums.BusinessType;
import com.hjm.project.formalPos.formalPos.domain.FormalPos;
import com.hjm.project.formalPos.formalPos.service.IFormalPosService;
import com.hjm.framework.web.controller.BaseController;
import com.hjm.framework.web.domain.AjaxResult;
import com.hjm.common.utils.poi.ExcelUtil;
import com.hjm.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * POS终端信息Controller
 * 
 * @author LOVE
 * @date 2020-11-26
 */
@Controller
@RequestMapping("/formalPos/formalPos")
public class FormalPosController extends BaseController
{
    private String prefix = "formalPos/formalPos";

    @Resource
    private IFormalPosService formalPosService;

    @Resource
    private IBranchPosService iBranchPosService;

    @Resource
    private IAgentInfoService iAgentInfoService;

    @Resource
    private IPurchaserUpdateRecordService iPurchaserUpdateRecordService;

    @Resource
    private IActivityUpdateRecordService iActivityUpdateRecordService;

    @Resource
    private IActActiveService iActActiveService;

    @Resource
    private ITerminalLibraryService iTerminalLibraryService;

    @Resource
    private IManufacturerService manufacturerService;


    @RequiresPermissions("formalPos:formalPos:view")
    @GetMapping()
    public String formalPos()
    {
        return prefix + "/formalPos";
    }

    /**
     * 查询POS终端信息列表
     */
    @RequiresPermissions("formalPos:formalPos:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(FormalPos formalPos) {
        if (ShiroUtils.isAgent()) {
            formalPos.setLoginAgentNum(ShiroUtils.getLoginAgentNum());
        }
        startPage();
        List<FormalPos> list = formalPosService.selectFormalPosList(formalPos);
        return getDataTable(list);
    }

    /**
     * 导出POS终端信息列表
     */
    @RequiresPermissions("formalPos:formalPos:export")
    @Log(title = "POS终端信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(FormalPos formalPos)
    {
        List<FormalPos> list = formalPosService.selectFormalPosList(formalPos);
        ExcelUtil<FormalPos> util = new ExcelUtil<FormalPos>(FormalPos.class);
        return util.exportExcel(list, "formalPos");
    }

    /**
     * 新增POS终端信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存POS终端信息
     */
    @RequiresPermissions("formalPos:formalPos:add")
    @Log(title = "POS终端信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(FormalPos formalPos)
    {
        return toAjax(formalPosService.insertFormalPos(formalPos));
    }

    /**
     * 修改POS终端信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        FormalPos formalPos = formalPosService.selectFormalPosById(id);
        mmap.put("formalPos", formalPos);
        return prefix + "/edit";
    }

    /**
     * 修改保存POS终端信息
     */
    @RequiresPermissions("formalPos:formalPos:edit")
    @Log(title = "POS终端信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(FormalPos formalPos)
    {
        return toAjax(formalPosService.updateFormalPos(formalPos));
    }

    /**
     * 删除POS终端信息
     */
    @RequiresPermissions("formalPos:formalPos:remove")
    @Log(title = "POS终端信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(formalPosService.deleteFormalPosByIds(ids));
    }

    @RequiresPermissions("formalPos:formalPos:merList")
    @GetMapping("merList")
    public String merList()
    {
        return prefix + "/merList";
    }


    /**
     * POS终端开关启停
     */
    @GetMapping("/shutPos/{id}")
    public String shutPos(@PathVariable("id") Long id, ModelMap mmap)
    {
        FormalPos formalPos = formalPosService.selectFormalPosById(id);
        mmap.put("formalPos", formalPos);
        return prefix + "/shutPos";
    }

    /**
     * 修改保存POS终端信息
     */
    @RequiresPermissions("formalPos:formalPos:shutPos")
    @Log(title = "POS终端信息", businessType = BusinessType.UPDATE)
    @PostMapping("/shutPos")
    @ResponseBody
    public AjaxResult shutPos(FormalPos formalPos)
    {
        return toAjax(formalPosService.updateFormalPos(formalPos));
    }

    @RequiresPermissions("formalPos:formalPos:ybFormalPos")
    @GetMapping("/ybFormalPos")
    public String ybFormalPos(ModelMap mmap) throws Exception {
        List<Map> manufacturer = manufacturerService.getManufacturer(ShiroUtils.isAgent() ? ShiroUtils.getLoginAgentNum() : null);
        mmap.put("manufacturer",manufacturer);
        return prefix + "/ybFormalPos";
    }


    /**
     * 查询POS终端信息列表
     */
    @PostMapping("/ybList")
    @ResponseBody
    public TableDataInfo ybList(FormalPos formalPos) {
        if (ShiroUtils.isSale()) {
            formalPos.setSaleAgentNum(ShiroUtils.getLoginAgentNum());
        }
        if (ShiroUtils.isAgent()) {
            formalPos.setLoginAgentNum(ShiroUtils.getLoginAgentNum());
        }
        Map map = formalPosService.selectFormalYbPosListCounter(formalPos);
        startPage();
        List<FormalPos> list = formalPosService.selectFormalYbPosList(formalPos);
        return getDataTable(list,map);
    }

    /**
     * 导出POS终端信息列表
     */
    @RequiresPermissions("formalPos:formalPos:ybExport")
    @Log(title = "终端明细查询导出", businessType = BusinessType.EXPORT)
    @PostMapping("/ybExport")
    @ResponseBody
    public AjaxResult ybExport(FormalPos formalPos) {
        if (ShiroUtils.isSale()) {
            formalPos.setSaleAgentNum(ShiroUtils.getLoginAgentNum());
        }
        if (ShiroUtils.isAgent()) {
            formalPos.setLoginAgentNum(ShiroUtils.getLoginAgentNum());
        }
        List<FormalPos> list = formalPosService.selectFormalYbPosList(formalPos);
        ExcelUtil<FormalPos> util = new ExcelUtil<FormalPos>(FormalPos.class);
        return util.exportExcel(list, "终端明细查询导出");
    }

    /**
     * 解绑终端
     */
    @Log(title = "解绑终端", businessType = BusinessType.INSERT)
    @PostMapping("/unbundlingMpos")
    @ResponseBody
    public AjaxResult unbundlingMpos(String posno, String merno) {
        AjaxResult ajaxResult = formalPosService.unbundlingMpos(posno, merno);
        return ajaxResult;
    }

    /**
     * 变更终端来源
     */
    @GetMapping("/onchagePosSource/{posno}")
    public String onchagePosSource(@PathVariable("posno") String posno, ModelMap mmap) {
        BranchPos branchPos = new BranchPos();
        branchPos.setPosno(posno);
        BranchPos branchPos1 = iBranchPosService.selectBranchPosList(branchPos).get(0);
        AgentInfo agentInfo = iAgentInfoService.selectAgentInfoById(branchPos1.getAgentNum().toString());
        mmap.put("fp",branchPos1);
        mmap.put("agent",agentInfo);
        return prefix + "/onchagePosSource";
    }

    /**
     * 变更终端活动到期日
     */
    @GetMapping("/onchagePosAct/{posno}")
    public String onchagePosAct(@PathVariable("posno") String posno, ModelMap mmap) {
        BranchPos branchPos = new BranchPos();
        branchPos.setPosno(posno);
        BranchPos branchPos1 = iBranchPosService.selectBranchPosList(branchPos).get(0);
        AgentInfo agentInfo = iAgentInfoService.selectAgentInfoById(branchPos1.getAgentNum().toString());
        mmap.put("fp",branchPos1);
        mmap.put("agent",agentInfo);
        return prefix + "/onchagePosAct";
    }
    /**
     * 变更终端活动到期日
     */
    @GetMapping("/returnObj/{posno}")
    public String returnObj(@PathVariable("posno") String posno, ModelMap mmap) {
        BranchPos branchPos = new BranchPos();
        branchPos.setPosno(posno);
        BranchPos branchPos1 = iBranchPosService.selectBranchPosList(branchPos).get(0);
        AgentInfo agentInfo = iAgentInfoService.selectAgentInfoById(branchPos1.getAgentNum().toString());
        mmap.put("fp",branchPos1);
        mmap.put("agent",agentInfo);
        return prefix + "/returnObj";
    }
    @GetMapping("/batchReturnObj")
    public String batchReturnObj(ModelMap mmap) {
        return prefix + "/batchReturnObj";
    }
    /**
     * 变更返现对象
     */
    @Log(title = "变更返现对象", businessType = BusinessType.INSERT)
    @PostMapping("/saveReturnObj")
    @ResponseBody
    public AjaxResult saveReturnObj(BranchPos branchPos) {
        try{

            AgentInfo act = iAgentInfoService.selectAgentInfoById(branchPos.getActAgentNum());
            AgentInfo re = iAgentInfoService.selectAgentInfoById(branchPos.getReachAgentNum());
            AgentInfo fl = iAgentInfoService.selectAgentInfoById(branchPos.getFlowAgentNum());
            AgentInfo st = iAgentInfoService.selectAgentInfoById(branchPos.getStaReachAgentNum());
            AgentInfo se = iAgentInfoService.selectAgentInfoById(branchPos.getServiceAgentNum());
            if (act == null) {
                return AjaxResult.error("激活返现对象代理不存在");
            } else if (re == null){
                return AjaxResult.error("达标返现对象代理不存在");
            } else if (fl == null){
                return AjaxResult.error("流量卡返现对象代理不存在");
            } else if (st == null){
                return AjaxResult.error("阶段达标返现对象代理不存在");
            } else if (se == null){
                return AjaxResult.error("服务费返现对象代理不存在");
            }

            BranchPos bp = iBranchPosService.selectBranchPosBySn(branchPos.getMachineNum());
           /* if (bp.getAgentNum().equals(String.valueOf(branchPos.getActAgentNum()))) {
                branchPos.setActive_type(0);
            } else {
                branchPos.setActive_type(1);
            }
            if (bp.getAgentNum().equals(String.valueOf(branchPos.getReachAgentNum()))) {
                branchPos.setStandard_type(0);
            } else {
                branchPos.setStandard_type(1);
            }
            if (bp.getAgentNum().equals(String.valueOf(branchPos.getFlowAgentNum()))) {
                branchPos.setFlow_type(0);
            } else {
                branchPos.setFlow_type(1);
            }
            if (bp.getAgentNum().equals(String.valueOf(branchPos.getStaReachAgentNum()))) {
                branchPos.setStage_standard_type(0);
            } else {
                branchPos.setStage_standard_type(1);
            }

            if (bp.getAgentNum().equals(String.valueOf(branchPos.getServiceAgentNum()))) {
                branchPos.setService_type(0);
            } else {
                branchPos.setService_type(1);
            }*/

            int i = iBranchPosService.updateBranchPos(branchPos);
            return toAjax(i);
        }catch (Exception e){
            throw e;
        }
    }
    /**
     * 变更返现对象
     */
    @Log(title = "变更返现对象", businessType = BusinessType.INSERT)
    @PostMapping("/saveBatchReturnObj")
    @ResponseBody
    public AjaxResult saveBatchReturnObj(@RequestParam Map<String,String> params,BranchPos branchPos) {
            String agentNum = params.get("agentNum");
            String level = params.get("level");
            if (StringUtils.isBlank(agentNum)) {
                return AjaxResult.error("请输入代理商编号");
            }
            if (StringUtils.isBlank(level)) {
                return AjaxResult.error("请选择变更规则");
            }
               String[] split = null;
        try {
                split = agentNum.split(",");
            for (String s : split) {
                AgentInfo agentInfo = iAgentInfoService.selectAgentInfoById(s);
                if (agentInfo == null) {
                    return AjaxResult.error("代理信息不存在【" + s + "】");
                }
            }
            } catch (Exception e) {
                return AjaxResult.error("输入的代理编号格式错误");
            }
        try{

            for (String agentnNum : split) {
                List<AgentInfo> agentInfos = new ArrayList<>();
                if ("2".equals(params.get("level"))) {
                    AgentInfo ai = new AgentInfo();
                    ai.setTopAgentNum(agentnNum);
                    agentInfos = iAgentInfoService.selectNextAgentInfoList(ai);
                } else if ("1".equals(params.get("level"))){
                    AgentInfo ai = new AgentInfo();
                    ai.setBelongAgent(Long.parseLong(agentnNum));
                    agentInfos = iAgentInfoService.selectAgentInfoList(ai);
                }

                for (AgentInfo agentInfo : agentInfos) {
                    long agentNumTar = Long.parseLong(agentInfo.getAgentNum());
                    AgentInfo act = iAgentInfoService.selectAgentInfoById(branchPos.getActAgentNum());
                    AgentInfo re = iAgentInfoService.selectAgentInfoById(branchPos.getReachAgentNum());
                    AgentInfo fl = iAgentInfoService.selectAgentInfoById(branchPos.getFlowAgentNum());
                    AgentInfo st = iAgentInfoService.selectAgentInfoById(branchPos.getStaReachAgentNum());
                    AgentInfo se = iAgentInfoService.selectAgentInfoById(branchPos.getServiceAgentNum());
                    if (act == null) {
                        return AjaxResult.error("激活返现对象代理不存在");
                    } else if (re == null){
                        return AjaxResult.error("达标返现对象代理不存在");
                    } else if (fl == null){
                        return AjaxResult.error("流量卡返现对象代理不存在");
                    } else if (st == null){
                        return AjaxResult.error("阶段达标返现对象代理不存在");
                    } else if (se == null){
                        return AjaxResult.error("服务费返现对象代理不存在");
                    }
                    BranchPos b = new BranchPos();
                    b.setAgentNum(agentNumTar);
                    List<BranchPos> branchPos1 = iBranchPosService.selectBranchPosList(b);
                    for (BranchPos pos : branchPos1) {
                        BranchPos bp = iBranchPosService.selectBranchPosBySn(pos.getMachineNum());
                       /* if (bp.getAgentNum().equals(String.valueOf(branchPos.getActAgentNum()))) {
                            branchPos.setActive_type(0);
                        } else {
                            branchPos.setActive_type(1);
                        }
                        if (bp.getAgentNum().equals(String.valueOf(branchPos.getReachAgentNum()))) {
                            branchPos.setStandard_type(0);
                        } else {
                            branchPos.setStandard_type(1);
                        }
                        if (bp.getAgentNum().equals(String.valueOf(branchPos.getFlowAgentNum()))) {
                            branchPos.setFlow_type(0);
                        } else {
                            branchPos.setFlow_type(1);
                        }
                        if (bp.getAgentNum().equals(String.valueOf(branchPos.getStaReachAgentNum()))) {
                            branchPos.setStage_standard_type(0);
                        } else {
                            branchPos.setStage_standard_type(1);
                        }

                        if (bp.getAgentNum().equals(String.valueOf(branchPos.getServiceAgentNum()))) {
                            branchPos.setService_type(0);
                        } else {
                            branchPos.setService_type(1);
                        }*/
                        branchPos.setId(bp.getId());
                        iBranchPosService.updateBranchPos(branchPos);

                    }
                }

            }
            return success();
        }catch (Exception e){
            throw e;
        }
    }




    /**
     * 变更终端来源
     */
    @Log(title = "变更终端来源", businessType = BusinessType.INSERT)
    @PostMapping("/onchagePosSourceData")
    @ResponseBody
    public AjaxResult onchagePosSourceData(BranchPos branchPos) {
        try{
            if (StringUtils.isEmpty(branchPos.getPosno())) {
                return error("请选择终端编号");
            }
            if (StringUtils.isEmpty(branchPos.getDqType())) {
                return error("请选择终端来源");
            }
            int i = iBranchPosService.updateBranchPos(branchPos);
            return toAjax(i);
        }catch (Exception e){
            throw e;
        }
    }

    /**
     * 变更活动过期日
     */
    @Log(title = "变更活动过期日", businessType = BusinessType.INSERT)
    @PostMapping("/onchagePosActEnd")
    @ResponseBody
    public AjaxResult onchagePosActEnd(BranchPos branchPos) {
        try{
            int i = iBranchPosService.updateBranchPos(branchPos);
            return toAjax(i);
        }catch (Exception e){
            throw e;
        }
    }

    /**
     * 批量变更购买人
     */
    @GetMapping("/updatePurchaser")
    public String updatePurchaser() {
        return prefix + "/updatePurchaser";
    }

    /**
     * 保存批量变更购买人
     */
    @PostMapping("/addUpdatePurchaser")
    @ResponseBody
    public AjaxResult addUpdatePurchaser(PurchaserUpdateRecord purchaserUpdateRecord, MultipartFile file, @RequestParam Map param){
        if (file == null || file.getSize() == 0) {
            return AjaxResult.warn("请上传正确的终端Excel文件");
        } else {
            File files = null;
            try {
                //解析file文件
                files = File.createTempFile("prefix", "_" + file.getOriginalFilename());
                file.transferTo(files);
                Map<String, Map<String, Object>> lines = PoiUtil.readExcelContent(files.getPath());
                //判断文件不为空
                if (lines.size() <= 0) {
                    return AjaxResult.warn("Excel文件为空,请重新上传");
                }
                if(lines.size() > 500){
                    return AjaxResult.warn("文件中SN数量不得超过500条！");
                }

                //失败sn集合（格式有误）
                List<String> snlist1 = new ArrayList<>();
                //失败sn集合（sn号不存在）
                List<String> snlist2 = new ArrayList<>();
                //失败sn集合（终端已激活）
                List<String> snlist3 = new ArrayList<>();
                //失败sn集合（SN号非划拨机具）
                List<String> snlist4 = new ArrayList<>();
                //失败sn集合（更改失败）
                List<String> snlist5 = new ArrayList<>();
                //失败sn集合（SN号不是同一人不允许修改）
                List<String> snlist6 = new ArrayList<>();
                //失败sn集合（活动不支持）
                List<String> snlist7 = new ArrayList<>();

                //成功数量
                int success = 0;
                //失败数量
                int error = 0;
                //获取此次变更批次号
                long batch = iPurchaserUpdateRecordService.selectPurchaserBatch();
                //便利文件sn，获取终端内容
                for (String key : lines.keySet()) {
                    String sn = lines.get(key).get("key0").toString();
                    //查询终端表
                    TerminalLibrary terminalLibrary = iTerminalLibraryService.selectTerminalLibraryBySn(sn);
                    //查询终端归属表，判断sn是否是划拨机具
                    BranchPos branchPos = iBranchPosService.selectBranchPosBySn(sn);
                    //判断sn号格式是否正确
                    if(!sn.matches("^[0-9a-zA-Z]+$")){
                        error ++;
                        purchaserUpdateRecord.setErrorNote("SN号格式有误");
                        snlist1.add(sn);
                        purchaserUpdateRecord.setUpdateType(1); //修改状态 失败
                    }else if (terminalLibrary != null && !terminalLibrary.equals(new TerminalLibrary())){    //判断终端号是否正确并存在
                        if (branchPos != null && !branchPos.equals(new BranchPos())) {//下一部判断

                            if (branchPos.getBuyerNum() == null || !branchPos.getBuyerNum().toString().equals(purchaserUpdateRecord.getBeforePurchaser())) {     //判断SN号是不是同一人
                                error ++;
                                purchaserUpdateRecord.setErrorNote("SN号不是同一人不允许修改");
                                snlist6.add(terminalLibrary.getMachineNum());
                                purchaserUpdateRecord.setUpdateType(1); //修改状态 失败

                            }else if(branchPos.getActivate() == null || !branchPos.getActivate().toString().equals("2")){     //终端激活后无法更改
                                error ++;
                                purchaserUpdateRecord.setErrorNote("终端已激活不允许修改");
                                snlist3.add(branchPos.getMachineNum());
                                purchaserUpdateRecord.setUpdateType(1);  //修改状态 失败

                            }else{
                                //创建新的参数对象
                                BranchPos branchPos1 = new BranchPos();
                                branchPos1.setBuyerNum(Long.parseLong(purchaserUpdateRecord.getLaterPurchaser()));//修改采购人
                                branchPos1.setId(branchPos.getId());

                                int result = iBranchPosService.updateBranchPos(branchPos1);
                                if(result <= 0){    //失败
                                    error ++;
                                    purchaserUpdateRecord.setErrorNote("变更失败");
                                    snlist5.add(branchPos.getMachineNum());
                                    purchaserUpdateRecord.setUpdateType(1); //修改状态 失败
                                }else{  /**成功 */
                                    purchaserUpdateRecord.setUpdateType(0);  //修改状态 成功
                                    success ++;
                                }
                            }
                        }else{
                            error ++;
                            purchaserUpdateRecord.setErrorNote("SN号非划拨机具");
                            snlist4.add(terminalLibrary.getMachineNum());
                            purchaserUpdateRecord.setUpdateType(1);  //修改状态 失败
                        }
                    }else{
                        error ++;
                        purchaserUpdateRecord.setErrorNote("SN号不存在");
                        snlist2.add(sn);
                        purchaserUpdateRecord.setUpdateType(1); //修改状态 失败
                    }
                    //sn
                    purchaserUpdateRecord.setSn(sn);
                    //修改人
                    purchaserUpdateRecord.setUpdateMan(this.getSysUser().getLoginName());
                    //修改时间
                    purchaserUpdateRecord.setUpdateDate(Utils.formateDate(2));
                    //终端型号
                    purchaserUpdateRecord.setModel(branchPos != null ? branchPos.getMachineModel() : "");
                    //批次号
                    purchaserUpdateRecord.setBatch(batch);
                    //保存修改记录
                    iPurchaserUpdateRecordService.insertPurchaserUpdateRecord(purchaserUpdateRecord);
                    //清空失败数据
                    purchaserUpdateRecord.setErrorNote("");

                }

                return AjaxResult.success("共"+((Integer)success+(Integer)error)+"台，"+success+"台：变更成功，"+error+"台：变更失败，"+ "其中" +
                        (snlist1.size() > 0 ? "，"+snlist1.size()+"台：SN号格式有误" : "") +
                        (snlist2.size() > 0 ? "，"+snlist2.size()+"台：SN号不存在" : "") +
                        (snlist3.size() > 0 ? "，"+snlist3.size()+"台：已激活不允许修改" : "") +
                        (snlist4.size() > 0 ? "，"+snlist4.size()+"台：SN号非划拨机具" : "") +
                        (snlist5.size() > 0 ? "，"+snlist5.size()+"台：更改失败" : "") +
                        (snlist6.size() > 0 ? "，"+snlist6.size()+"台：SN号不是同一人不允许修改" : "") +
                        (snlist7.size() > 0 ? "，"+snlist7.size()+"台：活动不支持" : "")
                );
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return AjaxResult.warn("修改失败！");

        }
    }

    /**
     * 批量变更活动
     */
    @GetMapping("/updateActivity")
    public String updateActivity() {
        return prefix + "/updateActivity";
    }

    /**
     * 保存批量变更活动
     */
    @PostMapping("/addUpdateActivity")
    @ResponseBody
    public AjaxResult addUpdateActivity(ActivityUpdateRecord activityUpdateRecord, MultipartFile file, @RequestParam Map param){
        if (file == null || file.getSize() == 0) {
            return AjaxResult.warn("请上传正确的终端Excel文件");
        } else {
            File files = null;
            try {
                //解析file文件
                files = File.createTempFile("prefix", "_" + file.getOriginalFilename());
                file.transferTo(files);
                Map<String, Map<String, Object>> lines = PoiUtil.readExcelContent(files.getPath());
                //判断文件不为空
                if (lines.size() <= 0) {
                    return AjaxResult.warn("Excel文件为空,请重新上传");
                }
                if(lines.size() > 500){
                    return AjaxResult.warn("文件中SN数量不得超过500条！");
                }

                //失败sn集合（格式有误）
                List<String> snlist1 = new ArrayList<>();
                //失败sn集合（sn号不存在）
                List<String> snlist2 = new ArrayList<>();
                //失败sn集合（终端已激活）
                List<String> snlist3 = new ArrayList<>();
                //失败sn集合（SN号非划拨机具）
                List<String> snlist4 = new ArrayList<>();
                //失败sn集合（更改失败）
                List<String> snlist5 = new ArrayList<>();
                //失败sn集合（SN号不是同一人不允许修改）
                List<String> snlist6 = new ArrayList<>();
                //失败sn集合（活动不支持）
                List<String> snlist7 = new ArrayList<>();

                //成功数量
                int success = 0;
                //失败数量
                int error = 0;
                //获取此次变更批次号
                long batch = iActivityUpdateRecordService.selectActivityBatch();
                //获取更改的活动信息
                ActActive actActive = iActActiveService.selectActActiveById(activityUpdateRecord.getLaterActivity());
                //便利文件sn，获取终端内容
                for (String key : lines.keySet()) {
                    String sn = lines.get(key).get("key0").toString();
                    //查询终端表
                    TerminalLibrary terminalLibrary = iTerminalLibraryService.selectTerminalLibraryBySn(sn);
                    //查询终端归属表，判断sn是否是划拨机具
                    BranchPos branchPos = iBranchPosService.selectBranchPosBySn(sn);
                    //判断sn号格式是否正确
                    if(!sn.matches("^[0-9a-zA-Z]+$")){
                        error ++;
                        activityUpdateRecord.setErrorNote("SN号格式有误");
                        snlist1.add(sn);
                        activityUpdateRecord.setUpdateType(1); //修改状态 失败
                    }else if (terminalLibrary != null && !terminalLibrary.equals(new TerminalLibrary())){    //判断终端号是否正确并存在
                        if (branchPos != null && !branchPos.equals(new BranchPos())) {//下一部判断

                            if (branchPos.getAgentNum() == null || !branchPos.getAgentNum().toString().equals(activityUpdateRecord.getAgent())) {     //判断SN号是不是同一人
                                error ++;
                                activityUpdateRecord.setErrorNote("SN号不是同一人不允许修改");
                                snlist6.add(terminalLibrary.getMachineNum());
                                activityUpdateRecord.setUpdateType(1); //修改状态 失败

                            }else if(branchPos.getPosType() != activityUpdateRecord.getPosType()){    //判断活动终端类型与SN终端类型是否一致
                                error ++;
                                activityUpdateRecord.setErrorNote("活动不支持");
                                snlist7.add(terminalLibrary.getMachineNum());
                                activityUpdateRecord.setUpdateType(1); //修改状态 失败

                            }else if(branchPos.getIsbound() == null || !branchPos.getIsbound().toString().equals("0")){     //终端激活后无法更改
                                error ++;
                                activityUpdateRecord.setErrorNote("终端已激活不允许修改");
                                snlist3.add(branchPos.getMachineNum());
                                activityUpdateRecord.setUpdateType(1);  //修改状态 失败

                            }else{
                                //记录修改前活动   //保存原活动编号
                                activityUpdateRecord.setBeforeActivity(branchPos.getActId() != null ? branchPos.getActId().toString() : "");
                                //创建新的参数对象
                                BranchPos branchPos1 = new BranchPos();
                                branchPos1.setActId(Long.parseLong(actActive.getActId()));   //修改活动编号
                                branchPos1.setActEnd(actActive.getEndTime());   //修改活动结束时间
                                branchPos1.setId(branchPos.getId());

                                int result = iBranchPosService.updateBranchPos(branchPos1);
                                if(result <= 0){    //失败
                                    error ++;
                                    activityUpdateRecord.setErrorNote("变更失败");
                                    snlist5.add(branchPos.getMachineNum());
                                    activityUpdateRecord.setUpdateType(1);  //修改状态 失败
                                }else{  /**成功 */
                                    activityUpdateRecord.setUpdateType(0);  //修改状态 成功
                                    success ++;
                                }
                            }
                        }else{
                            error ++;
                            activityUpdateRecord.setErrorNote("SN号非划拨机具");
                            snlist4.add(terminalLibrary.getMachineNum());
                            activityUpdateRecord.setUpdateType(1);  //修改状态 失败
                        }
                    }else{
                        error ++;
                        activityUpdateRecord.setErrorNote("SN号不存在");
                        snlist2.add(sn);
                        activityUpdateRecord.setUpdateType(1); //修改状态 失败
                    }
                    //sn
                    activityUpdateRecord.setSn(sn);
                    //修改人
                    activityUpdateRecord.setUpdateMan(this.getSysUser().getLoginName());
                    //修改时间
                    activityUpdateRecord.setUpdateDate(Utils.formateDate(2));
                    //终端型号
                    activityUpdateRecord.setModel(branchPos != null ? branchPos.getMachineModel() : "");
                    //批次号
                    activityUpdateRecord.setBatch(batch);
                    //保存修改记录
                    iActivityUpdateRecordService.insertActivityUpdateRecord(activityUpdateRecord);
                    //清空失败数据
                    activityUpdateRecord.setErrorNote("");

                }

                return AjaxResult.success("共"+((Integer)success+(Integer)error)+"台，"+success+"台：变更成功，"+error+"台：变更失败，"+ "其中" +
                        (snlist1.size() > 0 ? "，"+snlist1.size()+"台：SN号格式有误" : "") +
                        (snlist2.size() > 0 ? "，"+snlist2.size()+"台：SN号不存在" : "") +
                        (snlist3.size() > 0 ? "，"+snlist3.size()+"台：已激活不允许修改" : "") +
                        (snlist4.size() > 0 ? "，"+snlist4.size()+"台：SN号非划拨机具" : "") +
                        (snlist5.size() > 0 ? "，"+snlist5.size()+"台：更改失败" : "") +
                        (snlist6.size() > 0 ? "，"+snlist6.size()+"台：SN号不是同一人不允许修改" : "") +
                        (snlist7.size() > 0 ? "，"+snlist7.size()+"台：活动不支持" : "")
                );
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return AjaxResult.warn("修改失败！");

        }
    }

    @GetMapping("/exportFileAct")
    @ResponseBody
    public AjaxResult exportFileAct() {
        ExcelUtil<PosOperateModel> util = new ExcelUtil<PosOperateModel>(PosOperateModel.class);
        return util.importTemplateExcel("活动变更模板下载");
    }


}
